<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>custom validator local registration example</title>
    <script src="../../../node_modules/vue/dist/vue.js"></script>
    <script src="../../../dist/vue-validator.js"></script>
    <style>
      input.invalid { border-color: red; }
      .errors { color: red; }
    </style>
  </head>
  <body>
    <div id="app">
      <form novalidate>
        <div class="username">
          <label>username:</label>
          <validity field="username" :validators="['required']">
            <input type="text" name="username" @input="handleUsername">
          </validity>
        </div>
        <div class="age">
          <label>age:</label>
          <validity field="age" :validators="['numeric']">
            <input type="text" name="age" @input="handleAge">
          </validity>
        </div>
        <div class="site">
          <label>site:</label>
          <validity field="site" :validators="['url']">
            <input type="text" name="site" @input="handleSite">
          </validity>
        </div>
        <div class="errors">
          <p class="username" v-if="results.username.required">required username!!</p>
          <p class="age" v-if="results.age.numeric">invalid age numeric value!!</p>
          <p class="site" v-if="results.site.url">invlid url!!</p>
        </div>
        <input type="submit" value="send" v-if="valid">
      </form>
    </div>
    <script>
      new Vue({
        data: {
          results: {
            username: {},
            age: {},
            site: {}
          }
        },
        computed: {
          valid: function () {
            var results = this.results
            var fields = Object.keys(results)
            var ret = true
            for (var i = 0; i < fields.length; i++) {
              var field = fields[i]
              if (results[field].invalid) {
                ret = false
                break
              }
            }
            return ret
          }
        },
        validators: { // `numeric` and `url` custom validator is local registration
          numeric: function (val) {
            return /^[-+]?[0-9]+$/.test(val)
          },
          url: function (val) {
            return /^(http\:\/\/|https\:\/\/)(.{4,})$/.test(val)
          }
        },
        methods: {
          handleUsername: function (e) {
            this.handleValidate(e.target.$validity, 'username')
          },
          handleAge: function (e) {
            this.handleValidate(e.target.$validity, 'age')
          },
          handleSite: function (e) {
            this.handleValidate(e.target.$validity, 'site')
          },
          handleValidate: function ($validity, field) {
            var self = this
            $validity.validate(function () {
              var result = $validity.result
              self.results[field] = result
            })
          }
        }
      }).$mount('#app')
    </script>
  </body>
</html>
